<?php
namespace Home\Controller;
/**
 * 我的订单
 * User: linkwhy
 * Date: 2015/10/27
 * Time: 14:27
 */
class OrderController extends HomeController{

    private $wechar_id = 0;
    private $mode = '';
    private $item = '';

    public function _initialize(){
        $config = api('Config/lists');
        C($config); //添加配置
        $this->wechar_id = $_SESSION['wechat_id'];
        $this->mode = M('order');
        $this->item = M('order_item');
    }

    public function index(){

        //判断该用户是否有未有确认收货的状态
        $take_count = $this->mode->where(array('client_id' => $this->wechar_id, 'order_status' => 3))->count();
        if( $take_count > 0 ){
            //有确认收货的状态，那么自动判断该用户是否在规定的收货期限内确认收货
            $this->auto_sureGoods();
        }
        $type = I('get.type');
        $fields = 'o.id,o.order_id,order_status,pock_money,take_time,o.return_status,shop_id,is_clear';
        $where = array();
        $rgoods = M('return_goods');
        $ritem = M('return_item');
        switch($type){
            case 0:
                //全部
                $where = array('o.client_id' => $this->wechar_id);
                $data['name'] = '全部订单';
                break;
            case 1:
                //待付款
                $where = array('o.client_id' => $this->wechar_id, 'order_status' => 0);
                $data['name'] = '待付款';
                break;
            case 2:
                //待发货
                $where = array('o.client_id' => $this->wechar_id, 'order_status' => 2);
                $data['name'] = '待发货';
                break;
            case 3:
                //待收货
                $where = array('o.client_id' => $this->wechar_id, 'order_status' => 3);
                $data['name'] = '待收货';
                break;
        }
        if($type == 4){
            $list = $rgoods->alias('rg')->join('__ORDER__ o ON rg.order = o.order_id')->where(array('rg.client_id' => $this->wechar_id))->select();
            $data['name'] = '退货';
        }else{
            $list = $this->mode->alias('o')->field($fields)->where($where)->order('id desc')->select();
        }

        foreach($list as $key => &$val){
            $list[$key]['item'] = $this->item->alias('item')->field('item.order_id,c.goods_id,c.id as cart_id,g.name,g.picture,g.price,g.zhekou,c.num,c.color,c.size,shop_price,foot_width,foot_long,foot_thick')
                ->join('__CART__ c ON item.cart_id = c.id')
                ->join('__GOODS__ g ON c.goods_id = g.id')
                ->where(array('c.is_create' => 1, 'order_id' => $val['order_id']))->select();
            $val['is_take'] = 0;
            if( intval($val['order_status']) == 4){    //交易成功和未退货
                $val['is_take'] = $this->is_user_have_return($val['take_time'], $val['is_clear'], $val['shop_id'], $val['order_id']);
            }
        }


        foreach($list as $k => &$v){
            foreach($v['item'] as $k1 => &$v2){
                $row = $rgoods->alias('rg')->join('__RETURN_ITEM__ i ON i.order_id = rg.order_id')->where(array('order' => $v2['order_id'], 'goods_id' => $v2['goods_id'], 'cart_id' => $v2['cart_id']))->find();
                if($row){
                    $v2['return_status'] = $row['return_status'];
                }else{
                    $v2['return_status'] = 1;
                }
                $v2['priceAll'] = floatval($v2['price']) * intval($v2['num']);
                $v['count'] += $v2['num'];
                $v['zhekouAll'] += (floatval($v2['price']) * intval($v2['num'])) * (intval($v2['zhekou'])/100);
                unset($row);
            }
            $v['return_count'] = $rgoods->where(array('order' => $v['order_id'], 'type' => 'ALL', 'return_status' => 2))->count();
            $v['return_success_count'] = $rgoods->where(array('order' => $v['order_id'], 'type' => 'ALL', 'return_status' => 3))->count();
            $v['return_cancel_count'] = $rgoods->where(array('order' => $v['order_id'], 'type' => 'ALL', 'return_status' => 4))->count();
            //$v['return_all_count'] = $rgoods->where(array('order' => $v['order_id'], 'return_status' =>))
        }
        $data['shop_id'] = $_SESSION['shopid'];
        $data['user_id'] = $_SESSION['userid'];
        $this->assign('data', $data);
        $this->assign('list', $list);
        $this->assign('type', $type);
        $this->display();
    }

    public function return_index(){
        $rgoods = M('return_goods');

    }

    /**
     * 取消订单
     */
    public function cancel_order(){
        $data['order_status'] = 5;
        $data['msg'] = I('get.return_msg');
        if($this->mode->where(array('order_id' => I('get.order_id')))->save($data)){
            $this->ajaxReturn(array('status' => true));
        }else{
            $this->ajaxReturn(array('status' => false));
        }
    }

    public function order_index(){
        $ids = I('post.id');
        $cart = M('cart');
        $data = M('clients_address')->field('id,pro_id,city_id,area_id,name as sname,phone,address,code,default')->where(array(cid => $this->wechar_id, 'default' => 1))->find();   //收货地址
        $data['pro_name'] = $this->getAreaName($data['pro_id']);
        $data['city_name'] = $this->getAreaName($data['city_id']);
        $data['area_name'] = $this->getAreaName($data['area_id']);

        $list = array();
        $priceAll = 0;
        $goods_num = 0;
        foreach($ids as $k => $v){
             $list[] = $cart->alias('c')->field('g.id,g.name,g.picture,g.price,g.zhekou,c.id as cart_id,c.num,c.color,c.size,shop_price,foot_width,foot_long,foot_thick')
                ->join('__GOODS__ g ON c.goods_id = g.id')->where(array('c.id' => $v, 'client_id' => $this->wechar_id, 'is_create' => 0))->find();
        }

        foreach($list as $k1 => &$vo){
            $priceAll += $vo['price'] * $vo['num'];
            $goods_num += $vo['num'];
        }
        $data['name'] = '订单确认';
        $data['priceAll'] = $priceAll;
        $data['goods_num'] = $goods_num;
        $this->assign('list', $list);
        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 生成订单
     */
    public function create_order(){
        $cart_ids = I('post.cart_ids');
        if($cart_ids[0] != ''){
            $row = $this->mode->field('id')->order('id desc')->limit(1)->find();
            $rowcount1 = count($row) == 0 ? 0 : $row['id'];
            $cdh = "SHOES".date('Ymd')."-".$this->wechar_id."-".($rowcount1+1);       //生成订单号
            $data = array(
                'client_id' => $this->wechar_id,
                'order_id' => $cdh,
                'xf_money' => 0,
                'pock_money' => I('post.pock_money'),
                'order_status' => 0,
                'take_status' => 0,
                'return_status' => 0,
                'is_read' => 0,
                'ctime' => time(),
                'pay_time' => 0,
                'msg' => I('post.msg', ''),
                'take_id' => I('post.take_id'),
                'shop_id' => $_SESSION['shopid']
            );
            $this->mode->create($data);
            $cart = M('cart');
            $goods = M('goods');
            if($this->mode->add()){
                $add_data = array();
                $zhekou = 0;
                foreach($cart_ids as $key => $val){
                    $add_data[] = array('cart_id' => $val, 'order_id' => $cdh);
                    $cart->where(array('id' => $val))->setField('is_create', 1);
                    $row_temp = $cart->alias('c')->field('num,price,zhekou')->join('__GOODS__ g ON c.goods_id = g.id')->where(array('c.id' => $val, 'client_id' => $this->wechar_id))->find();
                    $zhekou += (floatval($row_temp['price']) * intval($row_temp['num'])) * (intval($row_temp['zhekou'])/100);
                }
                if(M('order_item')->addAll($add_data)){
                    header("Content-type: text/html; charset=utf-8");
                    $_SESSION['data'] = array('pock_money' => I('post.pock_money'), 'order_id' => $cdh, 'zhekouAll' => $zhekou);
//                    $this->redirect('order_success', '',2, '页面跳转中...');
                    //$this->order_success(I('post.pock_money'), $cdh, $zhekou);
                    $this->ajaxReturn(array('status' => true, 'url' => U('order_success')));
                }else{
                    //$this->error('订单生成失败!');
                    $this->ajaxReturn(array('status' => false, 'info' => '订单生成失败！'));
                }
            }
        }else{
            //$this->success('参数错误，正在跳转首页...', U('Index/index'));
            $this->ajaxReturn(array('status' => false, 'info' => '参数错误'));
        }
    }

    /**
     * 订单生成成功
     */
    public function order_success(){
        $data = M('clients_address')->field('id,pro_id,city_id,area_id,name as sname,phone,address,code,default')->where(array(cid => $this->wechar_id, 'default' => 1))->find();   //收货地址
        $data['pro_name'] = $this->getAreaName($data['pro_id']);
        $data['city_name'] = $this->getAreaName($data['city_id']);
        $data['area_name'] = $this->getAreaName($data['area_id']);
        $data['pock_money'] = $_SESSION['data']['pock_money'];
        $data['order_id'] = $_SESSION['data']['order_id'];
        $data['zhekouAll'] = $_SESSION['data']['zhekouAll'];
        $_SESSION['order_id'] = $_SESSION['data']['order_id'];
        $data['shop_id'] = $_SESSION['shopid'];
        $data['user_id'] = $_SESSION['userid'];
        $data['name'] = '立即支付';
        $this->assign('data', $data);
        $this->display();
    }

    public function getAreaName($area_id){
        $area = M('areas');
        $row = $area->field('area_name')->where(array('area_id' => $area_id))->find();
        return $row['area_name'];
    }

    /**
     * 查看物流
     */
    public function querywuliu(){
        //物流借口
        $exp = A('Express');
        $data = $this->mode->field('wl_order,wl_name')->where(array('order_id' => I('get.order_id')))->find();
        $data['name'] = '物流信息';
        $result  = $exp -> getorder( $data['wl_order']);
        $this->assign('list', $result['data']);
        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 确认收货
     */
    public function sureGoods(){
        $type = I('post.type', 0);
        $order_id = I('post.order_id');
        if($this->mode->where(array('order_id' => $order_id))->save(array('order_status' => 4, 'take_time' => time()))){
            if($type == 1){
                //用户确认并不退货的操作,实行放款的操作
                $shop_id = $this->mode->where(array('order_id' => $order_id))->getField('shop_id');
                $cr = A('ConfirmRefund');
                $rs = $cr->makeMoney($order_id, $shop_id);
                if($rs == 1){
                    //清算操作
                    if($this->mode->where(array('order_id' => $order_id))->setField('is_clear', 1)){
						$this->ajaxReturn(array('status' => true, 'info' => '交易清算成功！'));
					}else{
						$this->ajaxReturn(array('status' => true, 'info' => '交易清算失败！'));
					}
                }
            }else{
                $this->ajaxReturn(array('status' => true, 'info' => '交易成功！'));
            }
        }else{
            $this->ajaxReturn(array('status' => false, 'info' => '交易失败！'));
        }
    }

    /**
     * 自动判断用户收货时间
     */
    public function auto_sureGoods(){
        //读取收获期限天数
        $take_time = C('TAKETIME');
        $order = M('order');
        //获取卖家发货时间
        $list_time = $order->field('id,order_id,send_time')->where(array('client_id' => $this->wechar_id, 'order_status' => 3))->select();
        //计算收货期限的时间戳
        $temp_time = 60*60*24 * intval($take_time);
        $current_time = time();
        $end_time = 0;
        foreach($list_time as $key => $val){
            $end_time = $temp_time + intval($val['send_time']);
            if( $current_time > $end_time ){
                //更改订单状态为交易成功
                $order->where( array( 'id' => $val['id'], 'order_id' => $val['order_id'] ) )->save(array('order_status' => 4, 'take_time' => $current_time));
            }
        }
    }

    /**
     * 判断用户确认收货后在规定的退货时间内是否拥有退货功能
     */
    public function is_user_have_return($take_time, $is_claer, $shop_id, $order_id){
		if($is_claer == 1){
			//读取退货期限天数
			$return_time = C('RETURNTIME');
			//获取买家确认收货时间
			//计算退货期限的时间戳
			$end_time = 60*60*24 * intval( $return_time ) + intval($take_time);
			$current_time = time();
			if($current_time > $end_time){
				//过了退货时间
				if($is_claer == 0){
					//可以实现放款的操作
					$cr = A('ConfirmRefund');
					$rs = $cr->makeMoney($order_id, $shop_id);
					if($rs == 1){
						//清算操作
						$this->mode->where(array('order_id' => $order_id))->setField('is_clear', 1);
					}
				}
				return 1;
			}else{
				//未过退货时间
				return 0;
			}
		}else{
			//已经清算了
			return 1;
		}
        
    }
}

